package Thread.ThreadSynchronization;

/*
 * Author: JacksonCoder
 * FileName: SequentialExecutionWithCountDownLatch
 * Version: 1.0.0
 * Date: 2025/1/23
 */

import java.util.concurrent.CountDownLatch;

public class SequentialExecutionWithCountDownLatch {

    public static void main(String[] args) {
        // 创建2个CountDownLatch
        CountDownLatch latch1 = new CountDownLatch(1); // 控制 t1 和 t2 的顺序
        CountDownLatch latch2 = new CountDownLatch(1); // 控制 t2 和 t3 的顺序

        // 创建三个线程
        Thread t1 = new Thread(() -> {
            System.out.println("T1 is running");
            latch1.countDown(); // t1 执行完毕，释放 latch1
        });

        Thread t2 = new Thread(() -> {
            try {
                latch1.await(); // 等待 t1 执行完毕
                System.out.println("T2 is running");
                latch2.countDown(); // t2 执行完毕，释放 latch2
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        });

        Thread t3 = new Thread(() -> {
            try {
                latch2.await(); // 等待 t2 执行完毕
                System.out.println("T3 is running");
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        });

        // 启动三个线程
        t1.start();
        t2.start();
        t3.start();

        // 主线程等待t3执行完毕
        try {
            t3.join();
            System.out.println("this is main");
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        System.out.println("All threads have finished execution");

    }

}
